import React, { Component } from 'react'
import { Container, Content, Item, Toast, Root, Input } from 'native-base'
import { Actions } from 'react-native-router-flux'
import HeaderWhite from '../../components/header/headerWhite'
import { TextInput } from 'react-native'
import API from '../../api/request'
import { connect } from 'react-redux' // 引入connect函数
import * as userAction from '../../redux/actions/user'
import {validFn} from './valid'

class OneInput extends Component {
	constructor(props) {
		super(props)
		this.state = {
			inputValue: ''
		}
	}
	async _onSave() {
		const {
			apiMethod,
			params,
			paramKey,
			vali
		} = this.props.navigation.state.params
		let config = params || this.props.user
		config[paramKey] = this.state.inputValue || params[paramKey]
		let validRes = vali && validFn(vali, config[paramKey])
		if(validRes) {
			this.showMessage(validRes)
			return 
		}
		if (apiMethod) {
			API[apiMethod](config).then(info => {
				if (info._id) {
					Actions.pop()
				}
			})
		} else {
			let errMsg = await this.props.updateUserinfo({
				key: paramKey,
				val: config[paramKey]
			})
			if (errMsg) {
				this.showMessage(errMsg)
				return
			}
			Actions.pop()
		}
	}
	showMessage(text) {
		Toast.show({
			text: text,
			position: 'top',
			textStyle: {
				textAlign: 'center'
			},
			duration: 1000,
			type: 'danger'
		})
	}
	componentWillMount () {
		const params = this.props.navigation.state.params
		this.setState({
			inputValue: params.content
		})
	}
	render() {
		const params = this.props.navigation.state.params
		return (
			<Root>
				<Container>
					<HeaderWhite
						title={params.title || '编辑信息'}
						buttonText={params.saveText || '保存'}
						isDisabled={!this.state.inputValue}
						rightHandle={() => {
							this._onSave()
						}}
					/>

					<Content style={{ margin: 20 }}>
						<Item>
							<Input
								autoFocus
								placeholder={
									params.placeholder || '输入师傅收徒码'
								}
								placeholderTextColor={'#A5A5A5'}
								value={params.content}
								onChangeText={val => {
									params.content = val
									this.setState({
										inputValue: val
									})
								}}
							/>
						</Item>
					</Content>
				</Container>
			</Root>
		)
	}
}

export default connect(
	state => ({
		user: state.user.user
	}),
	dispatch => ({
		updateUserinfo: user => dispatch(userAction.updateUserInfo(user))
	})
)(OneInput)
